package org.mbari.dsg;

import com.sun.webui.jsf.model.Option;
import com.sun.webui.jsf.model.OptionsList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;
import org.mbari.vars.dao.DAOException;
import org.mbari.vars.knowledgebase.model.IConceptName;
import org.mbari.vars.knowledgebase.model.dao.KnowledgeBaseCache;
import org.slf4j.LoggerFactory;

/**
 * A Filter for use with the SearchBox in the DSG. See 
 * http://blogs.sun.com/dmitry/entry/creating_autocomplete_entry_field_with
 */
public class FilteredOptions extends OptionsList {
    
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(FilteredOptions.class);

    Option[] options = new Option[0]; //returned filtered options, built from props
    Properties props; //loaded props

    public FilteredOptions() {
        try {
            // Pre-load the Cache incase it's empty
            Collection conceptNames = KnowledgeBaseCache.getInstance().findAllConceptNames();
            filter(null); //initial data creation
        }
        catch (DAOException ex) {
            log.error("An error occurred while looking up ConceptNames from the VARS database", ex);
        }


    }

    public boolean filter(String filter) {
        
        Collection conceptNames = null;
        
        try {
            if (filter == null || filter.length() == 0 || filter.matches("^\\s+$")) {
                conceptNames =  KnowledgeBaseCache.getInstance().findAllConceptNames();
            }
            else {
                conceptNames = KnowledgeBaseCache.getInstance().findNamesBySubString(filter);
            }
        }
        catch (Exception e) {
            conceptNames = new ArrayList() {{
                add(IConceptName.NAME_DEFAULT);
            }};
            log.error("An error occurred while looking up ConceptNames from the VARS database", e);         
        }
        
        ArrayList names = new ArrayList(conceptNames);
                
        Collections.sort(names);
        //create new option list
        options = new Option[names.size()];
        int counter = 0;
        for (Object o : names) {
           // String cn = ((LWConceptName) o).getName();
            options[counter++] = new Option(o);
        }
        return true;
    }

    @Override
    public Option[] getOptions() {
        return options;
    }

    private void next() {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
